// Created by Kevin Tan
import 'package:assets_audio_player/assets_audio_player.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'dart:math';
import 'l10n/app_localizations.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SharedPreferences prefs = await SharedPreferences.getInstance();
  bool? agreedToTerms = prefs.getBool('agreedToTerms');

  runApp(MyApp(agreedToTerms: agreedToTerms ?? false));
}

class MyApp extends StatelessWidget {
  final bool agreedToTerms;

  MyApp({required this.agreedToTerms});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Wooden Bell',
      theme: ThemeData(
        primarySwatch: Colors.orange,
        brightness: Brightness.light,
      ),
      darkTheme: ThemeData(
        primarySwatch: Colors.orange,
        brightness: Brightness.dark,
      ),
      localizationsDelegates: const [
        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: AppLocalizations.supportedLocales,
      locale: null, // Use system locale
      home: agreedToTerms ? MainPage() : TermsPage(),
    );
  }
}

// 主页面 - 带底部导航栏
class MainPage extends StatefulWidget {
  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  int _currentIndex = 0;
  
  final List<Widget> _pages = [
    MuyuPage(),
    StatisticsPage(),
    SettingsPage(),
  ];

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    
    return Scaffold(
      body: _pages[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: l10n.navHome,
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.bar_chart),
            label: l10n.navStatistics,
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.settings),
            label: l10n.navSettings,
          ),
        ],
      ),
    );
  }
}

// 木鱼主页面
class MuyuPage extends StatefulWidget {
  @override
  _MuyuPageState createState() => _MuyuPageState();
}

class _MuyuPageState extends State<MuyuPage> with TickerProviderStateMixin {
  int _tapCount = 0;
  int _totalTapCount = 0;
  int _todayTapCount = 0;
  String _currentBlessing = '';
  bool _isAutoMode = false;
  bool _enableVibration = true;
  double _scale = 1.0;
  late AnimationController _animationController;
  late AnimationController _blessingController;

  @override
  void initState() {
    super.initState();
    _loadData();
    _animationController = AnimationController(
      duration: Duration(milliseconds: 100),
      vsync: this,
    );
    _blessingController = AnimationController(
      duration: Duration(milliseconds: 800),
      vsync: this,
    );
  }

  @override
  void dispose() {
    _animationController.dispose();
    _blessingController.dispose();
    super.dispose();
  }

  Future<void> _loadData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _totalTapCount = prefs.getInt('totalTapCount') ?? 0;
      _todayTapCount = prefs.getInt('todayTapCount') ?? 0;
      _enableVibration = prefs.getBool('enableVibration') ?? true;
      
      // 检查日期，如果是新的一天，重置今日计数
      String? lastDate = prefs.getString('lastDate');
      String today = DateTime.now().toString().split(' ')[0];
      if (lastDate != today) {
        _todayTapCount = 0;
        prefs.setInt('todayTapCount', 0);
        prefs.setString('lastDate', today);
      }
    });
  }

  Future<void> _saveData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt('totalTapCount', _totalTapCount);
    await prefs.setInt('todayTapCount', _todayTapCount);
    String today = DateTime.now().toString().split(' ')[0];
    await prefs.setString('lastDate', today);
  }

  void _playSound() {
    AssetsAudioPlayer.newPlayer().open(
      Audio("assets/sounds/muyu.mp3"),
      autoStart: true,
      showNotification: false,
      volume: 1.0,
    );
  }

  void _onTap(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    
    if (_enableVibration) {
      HapticFeedback.mediumImpact();
    }
    
    setState(() {
      _tapCount++;
      _totalTapCount++;
      _todayTapCount++;
      final blessings = l10n.blessings;
      _currentBlessing = blessings[Random().nextInt(blessings.length)];
      _scale = 0.9;
    });

    _playSound();
    _saveData();
    
    _animationController.forward().then((_) {
      setState(() {
        _scale = 1.0;
      });
      _animationController.reverse();
    });

    _blessingController.forward().then((_) {
      _blessingController.reverse();
    });
  }

  void _toggleAutoMode() {
    setState(() {
      _isAutoMode = !_isAutoMode;
    });

    if (_isAutoMode) {
      _startAutoMode();
    }
  }

  void _startAutoMode() {
    if (_isAutoMode) {
      _onTap(context);
      Future.delayed(Duration(milliseconds: 500), () {
        if (_isAutoMode && mounted) {
          _startAutoMode();
        }
      });
    }
  }

  String _getAchievementLevel(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    if (_totalTapCount < 100) return l10n.levelBeginner;
    if (_totalTapCount < 500) return l10n.levelNovice;
    if (_totalTapCount < 1000) return l10n.levelPractitioner;
    if (_totalTapCount < 5000) return l10n.levelDiligent;
    if (_totalTapCount < 10000) return l10n.levelEnlightened;
    return l10n.levelMaster;
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    
    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.appName),
        actions: [
          IconButton(
            icon: Icon(_isAutoMode ? Icons.pause : Icons.play_arrow),
            onPressed: _toggleAutoMode,
            tooltip: _isAutoMode ? l10n.stopAuto : l10n.autoMode,
          ),
        ],
      ),
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Colors.orange.shade50,
              Colors.orange.shade100,
            ],
          ),
        ),
        child: SafeArea(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              // 顶部统计信息
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: Card(
                  elevation: 4,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(15),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Column(
                      children: [
                        Text(
                          '${l10n.meritLevel}: ${_getAchievementLevel(context)}',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            color: Colors.orange.shade800,
                          ),
                        ),
                        SizedBox(height: 12),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: [
                            _buildStatItem(l10n.today, _todayTapCount.toString(), Icons.today),
                            _buildStatItem(l10n.session, _tapCount.toString(), Icons.timer),
                            _buildStatItem(l10n.total, _totalTapCount.toString(), Icons.stars),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ),

              // 祈福语显示
              FadeTransition(
                opacity: _blessingController,
                child: Text(
                  _currentBlessing,
                  style: TextStyle(
                    fontSize: 28,
                    fontWeight: FontWeight.bold,
                    color: Colors.orange.shade900,
                    shadows: [
                      Shadow(
                        blurRadius: 10.0,
                        color: Colors.orange.shade200,
                        offset: Offset(0, 0),
                      ),
                    ],
                  ),
                ),
              ),

              // 木鱼图片
              GestureDetector(
                onTap: () => _onTap(context),
                child: AnimatedScale(
                  scale: _scale,
                  duration: Duration(milliseconds: 100),
                  child: Container(
                    width: 280,
                    height: 280,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      boxShadow: [
                        BoxShadow(
                          color: Colors.orange.shade300.withOpacity(0.5),
                          blurRadius: 20,
                          spreadRadius: 5,
                        ),
                      ],
                    ),
                    child: Image.asset(
                      'assets/images/muyu.png',
                      fit: BoxFit.contain,
                    ),
                  ),
                ),
              ),

              // 提示文字
              Text(
                l10n.tapToAccumulate,
                style: TextStyle(
                  fontSize: 16,
                  color: Colors.grey.shade600,
                ),
              ),

              // 成就提示
              if (_totalTapCount > 0)
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 32.0),
                  child: LinearProgressIndicator(
                    value: (_totalTapCount % 100) / 100,
                    backgroundColor: Colors.grey.shade300,
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.orange),
                  ),
                ),
              
              SizedBox(height: 20),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildStatItem(String label, String value, IconData icon) {
    return Column(
      children: [
        Icon(icon, color: Colors.orange.shade700, size: 24),
        SizedBox(height: 4),
        Text(
          value,
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: Colors.orange.shade900,
          ),
        ),
        Text(
          label,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey.shade600,
          ),
        ),
      ],
    );
  }
}

// 统计页面
class StatisticsPage extends StatefulWidget {
  @override
  _StatisticsPageState createState() => _StatisticsPageState();
}

class _StatisticsPageState extends State<StatisticsPage> {
  int _totalTapCount = 0;
  int _todayTapCount = 0;
  int _weekTapCount = 0;
  List<Map<String, dynamic>> _achievements = [];

  @override
  void initState() {
    super.initState();
    _loadStatistics();
  }

  Future<void> _loadStatistics() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _totalTapCount = prefs.getInt('totalTapCount') ?? 0;
      _todayTapCount = prefs.getInt('todayTapCount') ?? 0;
      _weekTapCount = prefs.getInt('weekTapCount') ?? 0;
    });
  }

  List<Map<String, dynamic>> _getAchievements(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    return [
      {
        'title': l10n.achievementTitle(100),
        'description': l10n.achievementDescription(100),
        'count': 100,
        'unlocked': _totalTapCount >= 100,
        'icon': Icons.star,
      },
      {
        'title': l10n.achievementTitle(500),
        'description': l10n.achievementDescription(500),
        'count': 500,
        'unlocked': _totalTapCount >= 500,
        'icon': Icons.stars,
      },
      {
        'title': l10n.achievementTitle(1000),
        'description': l10n.achievementDescription(1000),
        'count': 1000,
        'unlocked': _totalTapCount >= 1000,
        'icon': Icons.auto_awesome,
      },
      {
        'title': l10n.achievementTitle(5000),
        'description': l10n.achievementDescription(5000),
        'count': 5000,
        'unlocked': _totalTapCount >= 5000,
        'icon': Icons.workspace_premium,
      },
      {
        'title': l10n.achievementTitle(10000),
        'description': l10n.achievementDescription(10000),
        'count': 10000,
        'unlocked': _totalTapCount >= 10000,
        'icon': Icons.emoji_events,
      },
      {
        'title': l10n.achievementTitle(50000),
        'description': l10n.achievementDescription(50000),
        'count': 50000,
        'unlocked': _totalTapCount >= 50000,
        'icon': Icons.military_tech,
      },
    ];
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    _achievements = _getAchievements(context);
    
    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.statistics),
      ),
      body: RefreshIndicator(
        onRefresh: _loadStatistics,
        child: ListView(
          padding: EdgeInsets.all(16),
          children: [
            // 统计卡片
            Card(
              elevation: 4,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(15),
              ),
              child: Padding(
                padding: const EdgeInsets.all(20.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      l10n.statisticsData,
                      style: TextStyle(
                        fontSize: 22,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 20),
                    _buildStatRow(l10n.todayMerit, _todayTapCount, Icons.today, Colors.blue),
                    Divider(),
                    _buildStatRow(l10n.weekMerit, _weekTapCount, Icons.date_range, Colors.green),
                    Divider(),
                    _buildStatRow(l10n.totalMerit, _totalTapCount, Icons.stars, Colors.orange),
                  ],
                ),
              ),
            ),

            SizedBox(height: 20),

            // 成就系统
            Text(
              l10n.achievements,
              style: TextStyle(
                fontSize: 22,
                fontWeight: FontWeight.bold,
              ),
            ),
            SizedBox(height: 10),

            ..._achievements.map((achievement) {
              return Card(
                elevation: 2,
                margin: EdgeInsets.only(bottom: 12),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
                child: ListTile(
                  leading: CircleAvatar(
                    backgroundColor: achievement['unlocked']
                        ? Colors.orange
                        : Colors.grey.shade300,
                    child: Icon(
                      achievement['icon'],
                      color: achievement['unlocked'] ? Colors.white : Colors.grey,
                    ),
                  ),
                  title: Text(
                    achievement['title'],
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: achievement['unlocked'] ? Colors.black : Colors.grey,
                    ),
                  ),
                  subtitle: Text(achievement['description']),
                  trailing: achievement['unlocked']
                      ? Icon(Icons.check_circle, color: Colors.green)
                      : Text(
                          '${(_totalTapCount / achievement['count'] * 100).toStringAsFixed(0)}%',
                          style: TextStyle(color: Colors.grey),
                        ),
                ),
              );
            }).toList(),

            SizedBox(height: 20),

            // 励志语录
            Card(
              color: Colors.orange.shade50,
              elevation: 2,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  children: [
                    Icon(Icons.format_quote, color: Colors.orange, size: 32),
                    SizedBox(height: 8),
                    Text(
                      l10n.quote,
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        fontSize: 16,
                        fontStyle: FontStyle.italic,
                        color: Colors.grey.shade700,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStatRow(String label, int value, IconData icon, Color color) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Row(
        children: [
          Icon(icon, color: color, size: 28),
          SizedBox(width: 12),
          Expanded(
            child: Text(
              label,
              style: TextStyle(fontSize: 16),
            ),
          ),
          Text(
            value.toString(),
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
        ],
      ),
    );
  }
}

// 设置页面
class SettingsPage extends StatefulWidget {
  @override
  _SettingsPageState createState() => _SettingsPageState();
}

class _SettingsPageState extends State<SettingsPage> {
  bool _enableVibration = true;
  bool _enableSound = true;
  bool _darkMode = false;
  String _appVersion = '';

  @override
  void initState() {
    super.initState();
    _loadSettings();
    _loadVersion();
  }

  Future<void> _loadVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    setState(() {
      _appVersion = '${packageInfo.version}+${packageInfo.buildNumber}';
    });
  }

  Future<void> _loadSettings() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _enableVibration = prefs.getBool('enableVibration') ?? true;
      _enableSound = prefs.getBool('enableSound') ?? true;
      _darkMode = prefs.getBool('darkMode') ?? false;
    });
  }

  Future<void> _saveSettings() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setBool('enableVibration', _enableVibration);
    await prefs.setBool('enableSound', _enableSound);
    await prefs.setBool('darkMode', _darkMode);
  }

  void _resetData(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(l10n.confirmReset),
          content: Text(l10n.resetMessage),
          actions: [
            TextButton(
              child: Text(l10n.cancel),
              onPressed: () => Navigator.of(context).pop(),
            ),
            TextButton(
              child: Text(l10n.confirm, style: TextStyle(color: Colors.red)),
              onPressed: () async {
                SharedPreferences prefs = await SharedPreferences.getInstance();
                await prefs.setInt('totalTapCount', 0);
                await prefs.setInt('todayTapCount', 0);
                await prefs.setInt('weekTapCount', 0);
                Navigator.of(context).pop();
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text(l10n.dataReset)),
                );
              },
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    
    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.settingsTitle),
      ),
      body: ListView(
        children: [
          SizedBox(height: 10),
          
          // 声音和振动设置
          _buildSectionTitle(l10n.soundAndVibration),
          SwitchListTile(
            title: Text(l10n.enableVibration),
            subtitle: Text(l10n.vibrationDesc),
            value: _enableVibration,
            onChanged: (value) {
              setState(() {
                _enableVibration = value;
              });
              _saveSettings();
            },
            secondary: Icon(Icons.vibration),
          ),
          SwitchListTile(
            title: Text(l10n.enableSound),
            subtitle: Text(l10n.soundDesc),
            value: _enableSound,
            onChanged: (value) {
              setState(() {
                _enableSound = value;
              });
              _saveSettings();
            },
            secondary: Icon(Icons.volume_up),
          ),

          Divider(),

          // 外观设置
          _buildSectionTitle(l10n.appearance),
          SwitchListTile(
            title: Text(l10n.darkMode),
            subtitle: Text(l10n.darkModeDesc),
            value: _darkMode,
            onChanged: (value) {
              setState(() {
                _darkMode = value;
              });
              _saveSettings();
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(content: Text(l10n.themeWillApply)),
              );
            },
            secondary: Icon(Icons.dark_mode),
          ),

          Divider(),

          // 数据管理
          _buildSectionTitle(l10n.dataManagement),
          ListTile(
            leading: Icon(Icons.refresh, color: Colors.orange),
            title: Text(l10n.resetData),
            subtitle: Text(l10n.resetDataDesc),
            onTap: () => _resetData(context),
          ),

          Divider(),

          // 关于
          _buildSectionTitle(l10n.about),
          ListTile(
            leading: Icon(Icons.info_outline),
            title: Text(l10n.appVersion),
            subtitle: Text(_appVersion),
          ),
          ListTile(
            leading: Icon(Icons.policy),
            title: Text(l10n.privacyPolicy),
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => PrivacyPolicyPage()),
              );
            },
          ),
          ListTile(
            leading: Icon(Icons.description),
            title: Text(l10n.userAgreement),
            onTap: () {
              _showUserAgreementDialog(context);
            },
          ),
          ListTile(
            leading: Icon(Icons.email),
            title: Text(l10n.contactUs),
            subtitle: Text('tan452301@live.com'),
          ),

          SizedBox(height: 20),

          // 版权信息
          Center(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Text(
                l10n.copyright,
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.grey.shade600,
                  fontSize: 12,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
      child: Text(
        title,
        style: TextStyle(
          fontSize: 14,
          fontWeight: FontWeight.bold,
          color: Colors.orange.shade700,
        ),
      ),
    );
  }
}

// 条款页面
class TermsPage extends StatelessWidget {
  void _showPrivacyPolicyDialog(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(l10n.privacyPolicy),
          content: SingleChildScrollView(
            child: Text(l10n.privacyPolicyContent),
          ),
          actions: <Widget>[
            TextButton(
              child: Text(l10n.close),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  void _showUserAgreementDialog(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(l10n.userAgreement),
          content: SingleChildScrollView(
            child: Text(l10n.userAgreementContent),
          ),
          actions: <Widget>[
            TextButton(
              child: Text(l10n.close),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    
    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.termsTitle),
      ),
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Colors.orange.shade50, Colors.white],
          ),
        ),
        child: Center(
          child: Padding(
            padding: const EdgeInsets.all(24.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Icon(
                  Icons.description,
                  size: 80,
                  color: Colors.orange,
                ),
                SizedBox(height: 30),
                Text(
                  l10n.welcomeToApp,
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(height: 20),
                Text(
                  l10n.termsIntro,
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 16),
                ),
                SizedBox(height: 30),
                ElevatedButton.icon(
                  icon: Icon(Icons.policy),
                  label: Text(l10n.readPrivacyPolicy),
                  style: ElevatedButton.styleFrom(
                    minimumSize: Size(double.infinity, 50),
                  ),
                  onPressed: () => _showPrivacyPolicyDialog(context),
                ),
                SizedBox(height: 15),
                ElevatedButton.icon(
                  icon: Icon(Icons.description),
                  label: Text(l10n.readUserAgreement),
                  style: ElevatedButton.styleFrom(
                    minimumSize: Size(double.infinity, 50),
                  ),
                  onPressed: () => _showUserAgreementDialog(context),
                ),
                SizedBox(height: 30),
                ElevatedButton(
                  child: Text(l10n.agreeAndContinue, style: TextStyle(fontSize: 16)),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.orange,
                    foregroundColor: Colors.white,
                    minimumSize: Size(double.infinity, 55),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  onPressed: () async {
                    SharedPreferences prefs = await SharedPreferences.getInstance();
                    await prefs.setBool('agreedToTerms', true);
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(builder: (context) => MainPage()),
                    );
                  },
                ),
                SizedBox(height: 15),
                OutlinedButton(
                  child: Text(l10n.disagreeAndExit),
                  style: OutlinedButton.styleFrom(
                    minimumSize: Size(double.infinity, 50),
                  ),
                  onPressed: () => SystemNavigator.pop(),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

// 隐私政策页面
class PrivacyPolicyPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    
    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.privacyPolicyAndAgreement),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: ListView(
          children: <Widget>[
            Card(
              elevation: 2,
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      l10n.privacyPolicy,
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 10),
                    Text(l10n.privacyPolicyContent),
                  ],
                ),
              ),
            ),
            SizedBox(height: 20),
            Card(
              elevation: 2,
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      l10n.userAgreement,
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 10),
                    Text(l10n.userAgreementContent),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

void _showUserAgreementDialog(BuildContext context) {
  final l10n = AppLocalizations.of(context)!;
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: Text(l10n.userAgreement),
        content: SingleChildScrollView(
          child: Text(l10n.userAgreementContent),
        ),
        actions: <Widget>[
          TextButton(
            child: Text(l10n.close),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ],
      );
    },
  );
}
